{% extends "后台管理/template.html" %}

{% block title %}
    版本管理
{% endblock %}

{% block css %}
<style>
    .version-card {
        background: #fff;
        border-radius: 8px;
        padding: 24px;
        margin-bottom: 20px;
        box-shadow: 0 2px 6px rgba(0,0,0,0.05);
        border: 1px solid #ebeef5;
    }
    
    .version-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 20px;
        padding-bottom: 15px;
        border-bottom: 1px solid #ebeef5;
    }
    
    .version-number {
        font-size: 18px;
        font-weight: 600;
        color: #333;
        display: flex;
        align-items: center;
        gap: 10px;
    }
    
    .version-badge {
        background: #696cff;
        color: #fff;
        padding: 4px 12px;
        border-radius: 20px;
        font-size: 13px;
    }
    
    .version-time {
        color: #999;
        font-size: 14px;
    }
    
    .update-list {
        margin: 0;
        padding: 0;
        list-style: none;
    }
    
    .update-item {
        display: flex;
        align-items: flex-start;
        margin-bottom: 12px;
        font-size: 14px;
    }
    
    .update-type {
        padding: 2px 8px;
        border-radius: 4px;
        margin-right: 10px;
        font-size: 12px;
        min-width: 48px;
        text-align: center;
    }
    
    .type-new {
        background: #e8f3ff;
        color: #1890ff;
    }
    
    .type-optimize {
        background: #f6ffed;
        color: #52c41a;
    }
    
    .type-fix {
        background: #fff2e8;
        color: #fa8c16;
    }
    
    .download-btn {
        background: #696cff;
        color: #fff;
        border: none;
        padding: 6px 16px;
        border-radius: 4px;
        font-size: 14px;
        display: inline-flex;
        align-items: center;
        gap: 6px;
        transition: all 0.3s ease;
    }
    
    .download-btn:hover {
        background: #5f62e6;
        transform: translateY(-1px);
    }
    
    .loading-overlay {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(255,255,255,0.8);
        display: flex;
        align-items: center;
        justify-content: center;
        z-index: 9999;
    }
    
    .empty-tip {
        text-align: center;
        padding: 40px 0;
        color: #999;
    }
    
    /* 更新内容展开/收起 */
    .update-list.collapsed {
        max-height: 120px;
        overflow: hidden;
        position: relative;
    }
    
    .update-list.collapsed::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 0;
        right: 0;
        height: 40px;
        background: linear-gradient(transparent, #fff);
    }
    
    .toggle-btn {
        color: #696cff;
        font-size: 14px;
        cursor: pointer;
        display: inline-flex;
        align-items: center;
        gap: 4px;
        margin-top: 10px;
        user-select: none;
    }
    
    .toggle-btn:hover {
        opacity: 0.8;
    }
    
    /* 分页样式 */
    .version-pagination {
        margin-top: 30px;
        display: flex;
        justify-content: center;
    }
    
    .version-pagination .page-link {
        color: #696cff;
        border-color: #e9ecef;
    }
    
    .version-pagination .page-item.active .page-link {
        background-color: #696cff;
        border-color: #696cff;
    }
    
    /* 更新说明列表容器样式 */
    #updateList {
        max-height: 300px;
        overflow-y: auto;
        padding-right: 5px;
    }
    
    /* 自定义滚动条样式 */
    #updateList::-webkit-scrollbar {
        width: 6px;
    }
    
    #updateList::-webkit-scrollbar-track {
        background: #f1f1f1;
        border-radius: 3px;
    }
    
    #updateList::-webkit-scrollbar-thumb {
        background: #696cff;
        border-radius: 3px;
    }
    
    #updateList::-webkit-scrollbar-thumb:hover {
        background: #5f62e6;
    }
    
    /* 更新说明项样式优化 */
    #updateList .alert {
        margin-bottom: 8px;
        padding: 10px 15px;
        border: 1px solid #ebeef5;
        background: #f8f9fa;
    }
    
    #updateList .alert:last-child {
        margin-bottom: 0;
    }
    
    /* 更新数量提示 */
    .update-count {
        font-size: 13px;
        color: #666;
        margin-bottom: 10px;
        padding-bottom: 10px;
        border-bottom: 1px solid #ebeef5;
    }
    
    .update-count .badge {
        background: #696cff;
        padding: 3px 8px;
        border-radius: 10px;
        color: #fff;
    }
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <!-- 添加版本按钮 -->
    <div class="mb-4">
        <button class="btn btn-primary" onclick="showAddVersionModal()">
            <i class='bx bx-plus me-1'></i>添加新版本
        </button>
    </div>

    <div id="versionList">
        <!-- 版本列表将通过JS动态插入 -->
    </div>
    
    <!-- 分页器 -->
    <nav class="version-pagination" aria-label="Version navigation" id="pagination" style="display: none;">
        <ul class="pagination">
            <!-- 分页按钮将通过JS动态插入 -->
        </ul>
    </nav>
    
    <!-- 加载中遮罩 -->
    <div class="loading-overlay" id="loadingOverlay" style="display: none;">
        <div class="spinner-border text-primary" role="status">
            <span class="sr-only">加载中...</span>
        </div>
    </div>

    <!-- 添加版本模态框 -->
    <div class="modal fade" id="addVersionModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">添加新版本</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="addVersionForm">
                        <!-- 版本号 -->
                        <div class="mb-3">
                            <label class="form-label">版本号</label>
                            <input 
                                type="text" 
                                class="form-control" 
                                id="versionInput" 
                                placeholder="请输入版本号，如：1.0.0"
                                pattern="^\d+\.\d+\.\d+$"
                                required
                            >
                            <div class="form-text text-muted">版本号格式：x.y.z（如：1.0.0）</div>
                        </div>
                        
                        <!-- 下载链接 -->
                        <div class="mb-3">
                            <label class="form-label">下载链接</label>
                            <input 
                                type="url" 
                                class="form-control" 
                                id="downloadUrlInput" 
                                placeholder="请输入安装包下载链接"
                                required
                            >
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="submitAddVersion()">
                        <i class='bx bx-save me-1'></i>下一步
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- 添加版本更新说明模态框 -->
    <div class="modal fade" id="addUpdateModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">添加版本更新说明</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <!-- 更新数量提示 -->
                    <div class="update-count">
                        已添加 <span class="badge" id="updateCount">0</span> 条更新说明
                    </div>
                    <div id="updateList" class="mb-3">
                        <!-- 更新说明列表将动态插入 -->
                    </div>
                    
                    <form id="addUpdateForm" class="border-top pt-3">
                        <div class="mb-3">
                            <label class="form-label">更新类型</label>
                            <select class="form-select" id="updateType">
                                <option value="1">新增</option>
                                <option value="2">修改</option>
                                <option value="3">删除</option>
                            </select>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">更新内容</label>
                            <textarea class="form-control" id="updateContent" rows="3" placeholder="请输入更新内容说明"></textarea>
                        </div>
                        
                        <button type="button" class="btn btn-info w-100" onclick="addUpdateItem()">
                            <i class='bx bx-plus-circle me-1'></i>添加更新说明
                        </button>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" onclick="cancelUpdate()">取消</button>
                    <button type="button" class="btn btn-primary" onclick="submitUpdates()">
                        <i class='bx bx-check me-1'></i>完成
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block js %}
<script>
// 分页相关变量
let currentPage = 1;
const pageSize = 5; // 每页显示5个版本
let latestVersion = '0.0.0'; // 存储最新版本号

// 获取版本列表
async function getVersionList() {
    try {
        showLoading();
        const response = await fetch('/api/system/get_system_version/', {
            method: 'GET'
        });
        
        const data = await response.json();
        
        if(data.code === 200) {
            // 分页处理
            const totalVersions = data.data;
            const totalPages = Math.ceil(totalVersions.length / pageSize);
            const start = (currentPage - 1) * pageSize;
            const end = start + pageSize;
            const currentVersions = totalVersions.slice(start, end);
            
            renderVersionList(currentVersions);
            renderPagination(totalVersions.length);
        } else {
            throw new Error(data.message);
        }
    } catch(error) {
        console.error('获取版本列表失败:', error);
        showToast('获取版本列表失败: ' + error.message, 'error');
    } finally {
        hideLoading();
    }
}

// 渲染版本列表
function renderVersionList(versions) {
    const container = document.getElementById('versionList');
    
    if(!versions || versions.length === 0) {
        container.innerHTML = `
            <div class="empty-tip">
                <i class='bx bx-info-circle fs-3 mb-2'></i>
                <p>暂无版本记录</p>
            </div>
        `;
        return;
    }
    
    // 验证版本号格式
    const isValidVersion = (version) => {
        return /^\d+\.\d+\.\d+$/.test(version);
    };
    
    // 按版本号排序（降序）
    versions.sort((a, b) => {
        if(!isValidVersion(a.version) || !isValidVersion(b.version)) return 0;
        const aVer = a.version.split('.').map(Number);
        const bVer = b.version.split('.').map(Number);
        for(let i = 0; i < 3; i++) {
            if(aVer[i] !== bVer[i]) return bVer[i] - aVer[i];
        }
        return 0;
    });
    
    // 更新最新版本号
    if(versions.length > 0 && isValidVersion(versions[0].version)) {
        latestVersion = versions[0].version;
    }
    
    container.innerHTML = versions.map((version, index) => `
        <div class="version-card">
            <div class="version-header">
                <div class="version-number">
                    <span>Version ${isValidVersion(version.version) ? version.version : '未知版本'}</span>
                    ${index === 0 ? `<span class="version-badge">最新版本</span>` : ''}
                </div>
                <div class="d-flex gap-2">
                    <button class="btn btn-outline-primary btn-sm" onclick="editVersionUpdates(${version.id})">
                        <i class='bx bx-edit-alt me-1'></i>编辑说明
                    </button>
                    <a href="${version.download_url}" class="download-btn" target="_blank">
                        <i class='bx bx-cloud-download'></i>
                        下载安装包
                    </a>
                </div>
            </div>
            
            <div class="version-time">
                <i class='bx bx-time'></i>
                发布时间：${formatDateTime(version.create_time)}
            </div>
            
            <div class="update-summary mb-3">
                <span class="badge bg-primary me-2">
                    <i class='bx bx-list-check me-1'></i>
                    ${version.update_data.length} 项更新
                </span>
            </div>
            
            <ul class="update-list ${version.update_data.length > 3 ? 'collapsed' : ''}" id="updateList-${version.id}">
                ${version.update_data.map(item => `
                    <li class="update-item">
                        <span class="update-type ${getTypeClass(item.update_type)}">
                            ${item.update_type}
                        </span>
                        <span class="update-content">${item.update_content}</span>
                    </li>
                `).join('')}
            </ul>
            
            ${version.update_data.length > 3 ? `
                <div class="toggle-btn" onclick="toggleUpdateList(${version.id})">
                    <span id="toggleText-${version.id}">展开更多</span>
                    <i class='bx bx-chevron-down' id="toggleIcon-${version.id}"></i>
                </div>
            ` : ''}
        </div>
    `).join('');
}

// 获取更新类型对应的样式类
function getTypeClass(type) {
    switch(type) {
        case '新增':
            return 'type-new';
        case '修改':
        case '优化':
            return 'type-optimize';
        case '修复':
        case '删除':
            return 'type-fix';
        default:
            return 'type-new';
    }
}

// 格式化日期时间
function formatDateTime(dateStr) {
    const date = new Date(dateStr.replace(/-/g, '/'));
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
    });
}

// 显示加载中
function showLoading() {
    document.getElementById('loadingOverlay').style.display = 'flex';
}

// 隐藏加载中
function hideLoading() {
    document.getElementById('loadingOverlay').style.display = 'none';
}

// 渲染分页器
function renderPagination(total) {
    const totalPages = Math.ceil(total / pageSize);
    if(totalPages <= 1) {
        document.getElementById('pagination').style.display = 'none';
        return;
    }
    
    const pagination = document.getElementById('pagination');
    pagination.style.display = 'flex';
    const ul = pagination.querySelector('ul');
    
    // 生成分页按钮
    let html = `
        <li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
            <a class="page-link" href="javascript:void(0)" onclick="changePage(${currentPage - 1})">
                <i class='bx bx-chevron-left'></i>
            </a>
        </li>
    `;
    
    for(let i = 1; i <= totalPages; i++) {
        html += `
            <li class="page-item ${currentPage === i ? 'active' : ''}">
                <a class="page-link" href="javascript:void(0)" onclick="changePage(${i})">${i}</a>
            </li>
        `;
    }
    
    html += `
        <li class="page-item ${currentPage === totalPages ? 'disabled' : ''}">
            <a class="page-link" href="javascript:void(0)" onclick="changePage(${currentPage + 1})">
                <i class='bx bx-chevron-right'></i>
            </a>
        </li>
    `;
    
    ul.innerHTML = html;
}

// 切换页码
function changePage(page) {
    const totalPages = Math.ceil(document.querySelectorAll('.version-card').length / pageSize);
    if(page < 1 || page > totalPages) return;
    
    currentPage = page;
    getVersionList();
    window.scrollTo(0, 0);
}

// 展开/收起更新列表
function toggleUpdateList(versionId) {
    const updateList = document.getElementById(`updateList-${versionId}`);
    const toggleText = document.getElementById(`toggleText-${versionId}`);
    const toggleIcon = document.getElementById(`toggleIcon-${versionId}`);
    
    if(updateList.classList.contains('collapsed')) {
        updateList.classList.remove('collapsed');
        toggleText.textContent = '收起';
        toggleIcon.classList.replace('bx-chevron-down', 'bx-chevron-up');
    } else {
        updateList.classList.add('collapsed');
        toggleText.textContent = '展开更多';
        toggleIcon.classList.replace('bx-chevron-up', 'bx-chevron-down');
    }
}

let addVersionModal = null;
let addUpdateModal = null;
let currentVersionId = null;
let updateItems = [];

// 初始化模态框
function initModals() {
    addVersionModal = new bootstrap.Modal(document.getElementById('addVersionModal'));
    addUpdateModal = new bootstrap.Modal(document.getElementById('addUpdateModal'));
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    getVersionList();
    initModals();
});

// 提交添加版本
async function submitAddVersion() {
    const versionInput = document.getElementById('versionInput');
    const downloadUrlInput = document.getElementById('downloadUrlInput');
    
    // 验证版本号格式
    const versionPattern = /^\d+\.\d+\.\d+$/;
    if(!versionPattern.test(versionInput.value)) {
        showToast('请输入正确的版本号格式：x.y.z', 'error');
        return;
    }
    
    // 验证新版本号是否大于当前最新版本
    const newVersion = versionInput.value.split('.').map(Number);
    const currentVersion = latestVersion.split('.').map(Number);
    let isNewer = false;
    
    for(let i = 0; i < 3; i++) {
        if(newVersion[i] > currentVersion[i]) {
            isNewer = true;
            break;
        } else if(newVersion[i] < currentVersion[i]) {
            showToast('新版本号必须大于当前最新版本', 'error');
            return;
        }
    }
    
    if(!isNewer) {
        showToast('新版本号必须大于当前最新版本', 'error');
        return;
    }
    
    // 验证下载链接
    if(!downloadUrlInput.value) {
        showToast('请输入下载链接', 'error');
        return;
    }
    
    try {
        showLoading();
        const response = await fetch('/api/system/add_system_version/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: `version=${encodeURIComponent(versionInput.value)}&download_url=${encodeURIComponent(downloadUrlInput.value)}`
        });
        
        const data = await response.json();
        
        if(data.code === 200) {
            // 保存版本ID并显示更新说明模态框
            currentVersionId = data.data.id;
            updateItems = [];
            addVersionModal.hide();
            showUpdateModal();
        } else {
            throw new Error(data.message);
        }
    } catch(error) {
        console.error('添加版本失败:', error);
        showToast('添加失败: ' + error.message, 'error');
    } finally {
        hideLoading();
    }
}

// 显示更新说明模态框
function showUpdateModal() {
    renderUpdateList();
    addUpdateModal.show();
}

// 渲染更新说明列表
function renderUpdateList() {
    const container = document.getElementById('updateList');
    const countBadge = document.getElementById('updateCount');
    
    // 更新数量显示
    countBadge.textContent = updateItems.length;
    
    if(updateItems.length === 0) {
        container.innerHTML = '<div class="text-muted text-center py-3">暂无更新说明</div>';
        return;
    }
    
    container.innerHTML = updateItems.map((item, index) => `
        <div class="alert d-flex align-items-center justify-content-between">
            <div class="d-flex align-items-center">
                <span class="badge ${getUpdateTypeBadgeClass(item.type)} me-2">${getUpdateTypeText(item.type)}</span>
                <span class="text-break">${item.content}</span>
            </div>
            <button type="button" class="btn btn-link text-danger p-0 ms-2 flex-shrink-0" onclick="removeUpdateItem(${index})">
                <i class='bx bx-trash'></i>
            </button>
        </div>
    `).join('');
    
    // 自动滚动到底部
    container.scrollTop = container.scrollHeight;
}

// 获取更新类型文本
function getUpdateTypeText(type) {
    const types = {
        '1': '新增',
        '2': '修改',
        '3': '删除'
    };
    return types[type] || '未知';
}

// 获取更新类型徽章样式
function getUpdateTypeBadgeClass(type) {
    const classes = {
        '1': 'bg-success',
        '2': 'bg-info',
        '3': 'bg-danger'
    };
    return classes[type] || 'bg-secondary';
}

// 添加更新说明项
function addUpdateItem() {
    const type = document.getElementById('updateType').value;
    const content = document.getElementById('updateContent').value.trim();
    
    if(!content) {
        showToast('请输入更新内容', 'error');
        return;
    }
    
    updateItems.push({
        type: type,
        content: content
    });
    
    document.getElementById('updateContent').value = '';
    document.getElementById('updateContent').focus(); // 保持输入框焦点
    renderUpdateList();
}

// 移除更新说明项
function removeUpdateItem(index) {
    updateItems.splice(index, 1);
    renderUpdateList();
}

// 取消更新
function cancelUpdate() {
    if(updateItems.length > 0) {
        if(!confirm('确定要取消吗？已添加的更新说明将丢失')) {
            return;
        }
    }
    addUpdateModal.hide();
    getVersionList(); // 刷新列表
}

// 提交更新说明
async function submitUpdates() {
    if(updateItems.length === 0) {
        showToast('请至少添加一条更新说明', 'error');
        return;
    }
    
    try {
        showLoading();
        
        // 提交新的更新说明
        for(const item of updateItems) {
            const response = await fetch('/api/system/add_system_version_update/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `system_version_id=${currentVersionId}&update_type=${item.type}&update_content=${encodeURIComponent(item.content)}`
            });
            
            const data = await response.json();
            if(data.code !== 200) {
                throw new Error(data.message);
            }
        }
        
        showToast('添加成功', 'success');
        addUpdateModal.hide();
        getVersionList(); // 刷新列表
        
    } catch(error) {
        console.error('添加更新说明失败:', error);
        showToast('添加失败: ' + error.message, 'error');
    } finally {
        hideLoading();
    }
}

// 显示添加版本模态框
function showAddVersionModal() {
    // 重置表单
    document.getElementById('addVersionForm').reset();
    
    // 更新模态框中的当前版本提示
    const form = document.getElementById('addVersionForm');
    const versionTipDiv = form.querySelector('.current-version-tip');
    
    if(!versionTipDiv) {
        // 如果提示div不存在，创建一个
        const tipDiv = document.createElement('div');
        tipDiv.className = 'current-version-tip alert alert-info mb-3';
        tipDiv.innerHTML = `
            <div class="d-flex align-items-center">
                <i class='bx bx-info-circle me-2'></i>
                <div>
                    <div class="fw-medium">当前最新版本</div>
                    <div class="text-primary fw-bold">v${latestVersion}</div>
                </div>
            </div>
        `;
        
        // 插入到表单最前面
        form.insertBefore(tipDiv, form.firstChild);
    } else {
        // 如果提示div存在，更新内容
        versionTipDiv.querySelector('.text-primary').textContent = `v${latestVersion}`;
    }
    
    addVersionModal.show();
}

// 编辑版本说明
function editVersionUpdates(versionId) {
    try {
        currentVersionId = versionId;
        updateItems = []; // 清空更新项，只添加新的更新说明
        showUpdateModal();
    } catch(error) {
        console.error('获取版本更新说明失败:', error);
        showToast('获取失败: ' + error.message, 'error');
    }
}

// 获取更新类型值
function getUpdateTypeValue(typeText) {
    const typeMap = {
        '新增': '1',
        '修改': '2',
        '优化': '2',
        '删除': '3',
        '修复': '3'
    };
    return typeMap[typeText.trim()] || '1';
}
</script>
{% endblock %}

{% block nav_left %}
{% endblock %}

{% block NavBar %}
{% include '后台管理/components/左侧导航栏.html' %}
{% endblock %}

{% block footer %}
{% include '后台管理/components/Footer.html' %}
{% endblock %}
